public class PhiEat_2 {

    public static void main(String[] args) {
        Chop fiveChops = new Chop();
        new Philosopher(0, fiveChops).start();
        new Philosopher(1, fiveChops).start();
        new Philosopher(2, fiveChops).start();
        new Philosopher(3, fiveChops).start();
        new Philosopher(4, fiveChops).start();
    }
}

class Philosopher extends Thread {
    private int index;
    private Chop chop;

    public Philosopher(int index, Chop chop) {
        this.index = index;
        this.chop = chop;
    }

    @Override
    public void run() {
        while (true) {
            thinking();
            chop.takeChop(index);
            eating();
            chop.putChop(index);
        }
    }

    private void thinking() {
        System.out.println("第" + index + "个哲学家正在思考...");
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void eating() {
        System.out.println("第" + index + "个哲学家正在吃饭...");
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Chop {
    public static int[] chops = {1, 1, 1, 1, 1};

    public synchronized void takeChop (int index) {
        while (chops[index] == 0 || chops[(index + 1) % 5] == 0) {
            try {
                wait();
            } catch (Exception e) {

            }
        }
        chops[index] = 0;
        chops[(index + 1) % 5] = 0;
    }

    public synchronized void putChop(int index) {
        chops[index] = 1;
        chops[(index + 1) % 5] = 1;
        notifyAll();
    }
}
